import Link from 'next/link';
import type { IPost } from '@/interfaces';
import { useMutation } from '@tanstack/react-query';
import type { TBody } from '@/types';
import { postView } from '@/services/api';
import classNames from 'classnames';
import { useContext } from 'react';
import { UserIdPageContext } from '@/contexts/user-id';

export default function PostReadMoreBtn({
  item,
  isEdit,
  btnClassName,
}: {
  item: IPost;
  isEdit?: boolean;
  btnClassName?: string;
}) {
  const { id, contentType, contentLink } = item;
  const isLink = contentType === 'LINK' && contentLink;
  const { translatedFields } = useContext(UserIdPageContext)!;

  const postViewMutation = useMutation(async (variables: TBody<void>) => {
    await postView(variables);
  });

  function onClickLink() {
    postViewMutation.mutateAsync({
      id,
    });
  }

  if (isEdit) {
    return (
      <Link
        className={classNames('btn btn-primary', btnClassName)}
        href={`/posts/${item.id}/edit`}
      >
        <i className="bi bi-pencil-square me-2"></i>
        {translatedFields.editPost}
      </Link>
    );
  }

  return (
    <>
      {isLink ? (
        <Link
          onClick={onClickLink}
          href={contentLink}
          className={classNames('btn btn-primary', btnClassName)}
          rel="noopener noreferrer"
          target="_blank"
        >
          <i className="bi bi-book me-2"></i>
          {translatedFields.readMore}
        </Link>
      ) : (
        <Link
          className={classNames('btn btn-primary', btnClassName)}
          href={`/posts/${item.id}`}
        >
          <i className="bi bi-book me-2"></i>
          {translatedFields.readMore}
        </Link>
      )}
    </>
  );
}
